const vorpal = require('vorpal')()
const Table = require('cli-table')
const BlockChain = require('./blockchain')
const rsa = require('./rsa')
const blockchain = new BlockChain()


function formatLog(data) {
  if(!data || data.length===0) {
    return
  }
  if (!Array.isArray(data)) {
    data = [data]
  }

  const first = data[0]
  console.log(first)
  const head = Object.keys(first)

  // instantiate
  const table = new Table({
    head: head,
    colWidths: new Array(head.length).fill(20)
  });

  const res = data.map(v => {
    return head.map(h => JSON.stringify(v[h], null, 1))
  })
  table.push(...res);
  console.log(table.toString());
}


vorpal
  .command('mine', 'mine -- 挖矿')
  .action(function (args, callback) {
    const newBlock = blockchain.mine(rsa.keys.pub)
    if (newBlock) {
      formatLog(newBlock)
    }
    callback()
  })

vorpal
  .command('blockchain', 'chain ---查看区块链')
  .action(function (args, callback) {
    formatLog(blockchain.blockchain)
    callback()
  })

vorpal
  .command('transfer <to> <amount>', 'transfer -- 转账交易')
  .action(function (args, callback) {
    // 本地公钥当做转出地址
    let trans = blockchain.transfer(rsa.keys.pub, args.to, args.amount)
    formatLog(trans)
    callback()
  })

vorpal
  .command('balance <address>', 'balance -- 查看余额')
  .action(function (args, callback) {
    const balance = blockchain.balance(args.address)
    if (balance) {
      formatLog({
        balance,
        address: args.address
      })
    }
    callback()
  })

vorpal
  .command('pub', '查看本地地址(公钥)')
  .action(function (args, callback) {
    console.log(rsa.keys.pub)
    callback()
  })

vorpal
  .command('peers', '查看网络节点列表')
  .action(function (args, callback) {
    formatLog(blockchain.peers)
    callback()
  })

vorpal
  .command('chat <msg>', '跟别的节点打招呼')
  .action(function (args, callback) {
    blockchain.boardcast({
      type: 'hi',
      data: args.msg
    })
    callback()
  })

vorpal
  .command('pending', '查看还没被打包的交易')
  .action(function (args, callback) {
    formatLog(blockchain.data)
    callback()
  })

  
console.log('welcom to chain')
vorpal.exec('help')
vorpal
  .delimiter('chain=>')
  .show()